package com.kuaiditu.assistant.ui.main;

import android.support.annotation.Nullable;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.ParamsAnalog;
import com.kuaiditu.assistant.api.xz_api.XingZheApi;
import com.kuaiditu.assistant.api.yd_api.entity.DaoSession;
import com.kuaiditu.assistant.api.zzt_api.ZZTApi;
import com.kuaiditu.assistant.dagger.components.AppComponent;
import com.kuaiditu.assistant.entity.ExpressCom;
import com.kuaiditu.assistant.entity.Operator;
import com.kuaiditu.assistant.entity.OperatorDao;
import com.kuaiditu.assistant.entity.TaskSquareEn;
import com.kuaiditu.assistant.util.JudgeExpressUtil;
import com.kuaiditu.assistant.util.LogUtil;
import com.kuaiditu.assistant.util.OrderStateUtil;
import com.kuaiditu.assistant.util.ToastUtil;
import com.yunda.crypt.NativeEncryption;

import java.io.IOException;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Eenie on 2017/8/30.
 * Email: eeniework@gmail.com
 * Des:
 */

public class AwaitTaskAdapter extends BaseQuickAdapter<TaskSquareEn, BaseViewHolder> {

    private DaoSession mDaoSession;
    private OperatorDao mOperatorDao;
    private ParamsAnalog mParamsAnalog;
    private XingZheApi mXingZheApi;
    private ZZTApi mZZTApi;

    public AwaitTaskAdapter(@Nullable List<TaskSquareEn> data, AppComponent appComponent) {
        super(R.layout.item_await_task, data);
        mDaoSession = appComponent.getDaoSession();
        mOperatorDao = mDaoSession.getOperatorDao();
        mParamsAnalog = appComponent.getParamsAnalog();
        mXingZheApi = appComponent.getApiManager().getXingZheApi();
        mZZTApi = appComponent.getApiManager().getZZTApi();
    }

    @Override
    protected void convert(BaseViewHolder helper, TaskSquareEn item) {


//        String taskInfo = String.format("%s至%s,共%s天 预计%s单/天", mSimpleDateFormat.format(item.getOrder_startTime()),
//                mSimpleDateFormat.format(item.getOrder_endTime()), item.getOrder_dayNum(), item.getOrder_sendOrderNum());


        String takeAddress = String.format("%s%s%s%s", item.getOrder_getProvinceName(),
                item.getOrder_getCityName(),
                item.getOrder_getDistrictName(),
                item.getOrder_getAddress());
        String sendAddressStart = String.format("%s%s%s%s%s", item.getOrder_sendProvinceName(), item.getOrder_sendCityName()
                , item.getOrder_sendDistrictName(),
                item.getOrder_sendAddress(), item.getOrder_sendStartAddress());
        String sendAddressEnd = String.format("%s%s%s%s%s", item.getOrder_sendProvinceName(), item.getOrder_sendCityName()
                , item.getOrder_sendDistrictName(),
                item.getOrder_sendAddress(), item.getOrder_sendEndAddress());

        TextView tvCom = helper.getView(R.id.tv_express_com);

        JudgeExpressUtil.analyze(item.getOrder_netsite(), tvCom);

        helper.setText(R.id.tv_task_state, OrderStateUtil.getOrderStateDes(item.getOrder_status()));

        Operator operator = mOperatorDao.queryBuilder()
                .where(OperatorDao.Properties.Task_id.eq(item.getOrder_id())).unique();

        if (operator != null && item.getOrder_netsite() != null) {
            switch (item.getOrder_netsite().getNetsite_expressCompanyId()) {
                case ExpressCom.EXPRESS_COM_CODE_YD:
                    initYd(helper, operator);
                    break;
                case ExpressCom.EXPRESS_COM_CODE_ZT:
                    initZT(helper, operator);
                    break;
                case ExpressCom.EXPRESS_COM_CODE_YT:
                    initYT(helper, operator);
                    break;
                case ExpressCom.EXPRESS_COM_CODE_ST:
                    initST(helper, operator);
                    break;
                default:
                    initYT(helper, operator);
                    break;
            }


        } else {
            helper.setText(R.id.tv_operator_name, "派件人：--");
            helper.setText(R.id.tv_operator_account, "派件账号：--");
        }
        item.setOperator(operator);
        helper.setText(R.id.tv_express_address, takeAddress)
                .setText(R.id.tv_take_task_plan_count, String.valueOf(item.getOrder_sendOrderNum()))
                .setText(R.id.tv_take_task_fact_count, String.format("已经确认录入%s单", item.getOrder_addOrderNum()))
                .setText(R.id.tv_take_send_plan_count, String.valueOf(item.getOrder_addOrderNum()))
                .setText(R.id.tv_take_send_fact_count, String.format("已经确认录入%s单", item.getOrder_signOrderNum()));

        helper.addOnClickListener(R.id.img_camera_take_delivery);
        helper.addOnClickListener(R.id.img_camera_send_delivery);
        helper.addOnClickListener(R.id.btn_thirdparty);
    }

    private void initST(BaseViewHolder helper, Operator operator) {
        helper.setText(R.id.tv_operator_name, "派件人：" + operator.getName());
        helper.setText(R.id.tv_operator_account, "派件账号：" + operator.getAccout());
    }

    private void initZT(final BaseViewHolder helper, final Operator operator) {
        mZZTApi.refreshToken(operator)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new DefaultObserver<ResponseBody>() {
            @Override
            public void onNext(@NonNull ResponseBody responseBody) {
                try {
                    JSONObject resJson = JSON.parseObject(responseBody.string());
                    if (resJson.containsKey("access_token")) {
                        helper.setText(R.id.tv_operator_name, "派件人：" + operator.getName());
                        helper.setText(R.id.tv_operator_account, "派件账号：" + operator.getAccout());
                        String access_token = resJson.getString("access_token");
                        String refresh_token =  resJson.getString("refresh_token");
                        String openid = resJson.getString("openid");
                        operator.setZt_openId(openid);
                        operator.setZt_token(access_token);
                        operator.setZt_refresh_token(refresh_token);
                        mOperatorDao.insertOrReplace(operator);
                    } else {
                        ToastUtil.showToast("账号失效，请重新登录");
                        helper.setText(R.id.tv_operator_name, "派件人：--");
                        helper.setText(R.id.tv_operator_account, "派件账号：--");
                        delOperator(operator);
                        notifyItemChanged(helper.getPosition());
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                    ToastUtil.showToast("账号失效，请重新登录");
                    helper.setText(R.id.tv_operator_name, "派件人：--");
                    helper.setText(R.id.tv_operator_account, "派件账号：--");
                    delOperator(operator);
                    notifyItemChanged(helper.getPosition());
                }

            }

            @Override
            public void onError(@NonNull Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast("账号失效，请重新登录");
                helper.setText(R.id.tv_operator_name, "派件人：--");
                helper.setText(R.id.tv_operator_account, "派件账号：--");
                delOperator(operator);
                notifyItemChanged(helper.getPosition());
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void initYT(final BaseViewHolder helper, final Operator operator) {
        helper.setText(R.id.tv_operator_name, "派件人：" + operator.getName());
        helper.setText(R.id.tv_operator_account, "派件账号：" + operator.getAccout());
    }


    private void initYd(final BaseViewHolder helper, final Operator operator) {
        Observable.just(operator)
                .subscribeOn(Schedulers.io())
                .map(new Function<Operator, Boolean>() {
                    @Override
                    public Boolean apply(@NonNull Operator operator) throws Exception {
                        int res = NativeEncryption.JNI_EDCodeInstance(ParamsAnalog.YD_HOST, ParamsAnalog.YD_PORT, operator.getYd_token(), ParamsAnalog.YD_APP_VER, operator.getYd_public_key());
                        LogUtil.e("yd encode util init res = " + res);
                        return res == 0;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<Boolean>() {
                    @Override
                    public void onNext(@NonNull Boolean init) {
                        if (init) {
                            helper.setText(R.id.tv_operator_name, "派件人：" + operator.getName());
                            helper.setText(R.id.tv_operator_account, "派件账号：" + operator.getAccout());
                        } else {
                            ToastUtil.showToast("账号失效，请重新登录");
                            helper.setText(R.id.tv_operator_name, "派件人：--");
                            helper.setText(R.id.tv_operator_account, "派件账号：--");
                            delOperator(operator);
                            notifyItemChanged(helper.getPosition());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void delOperator(Operator operator) {
        mOperatorDao.delete(operator);
    }


}
